package com.example.survey23.controller;


import com.example.survey23.common.lang.Result;
import com.example.survey23.entity.GroupLog;
import com.example.survey23.service.GroupLogService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 23Group
 * @since 2022-11-05
 */
@Slf4j
@RestController
@RequestMapping("/group-log")
public class GroupLogController {

    @Autowired
    GroupLogService groupLogService;


    // 创建群组记录 —— 以 mapper 接收前端传入数据
    @PostMapping("/save")
    public Result saveGroup(@RequestBody HashMap map){
        String usersId = (String) map.get("usersId"); // 得到含有全部记录信息的字符串
        Long tenantId = Long.parseLong(map.get("tenantId").toString()); // 强制转换为 Long
        Long groupId =  Long.parseLong(map.get("groupId").toString());
        String[] arrayUserId = usersId.split(",");
        log.info("长度为" + arrayUserId.length);

        long maxId = groupLogService.getMaxGroupLogId() + 1; // 得到当前最大的 id, 以便后续使用自增 id

        for(String id: arrayUserId){ // 保存每条记录
            Long uid = Long.parseLong(id);
            GroupLog groupLog = new GroupLog();
            groupLog.setOwner(tenantId);
            groupLog.setMember(uid);
            groupLog.setGroupId(groupId);
            groupLogService.saveOrUpdate(groupLog);
        }
        return Result.succ(null);
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody HashMap map){
        long groupId = Long.parseLong((String)map.get("groupId"));
        long memberId = Long.parseLong((String)map.get("memberId"));
        Long id = groupLogService.getDeleteId(groupId, memberId);
        return groupLogService.removeById(id) ? Result.succ(null) : Result.fail(null);
    }



}
